package jwt

import (
	"dy/internal/configs/config"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

//jwt,token验证
var jwtKey []byte

type MyClaims struct {
	UserId int `json:"user_id"`
	jwt.StandardClaims
}

func GetToken(userId int) (string, error) {
	appSecret := config.Conf.UserWeb.ApiSecret
	jwtKey = []byte(appSecret)
	claim := &MyClaims{
		UserId: userId,
		StandardClaims: jwt.StandardClaims{
			IssuedAt: time.Now().Unix(),
			Subject:  "userToken",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}
func ParseToken(tokenString string) (int, error) {
	claim := &MyClaims{}
	jwtKey = []byte(config.Conf.UserWeb.ApiSecret)
	token, err := jwt.ParseWithClaims(tokenString, claim, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err == nil && token != nil {
		if token.Valid {
			return claim.UserId, nil
		} else {
			return -1, errors.New("token解析失败")
		}
	}

	return -1, err

}
